# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from apps.news.services.compiler import Compiler
from core.models import Category
from core.libs.mysqlfulltextsearch.search_manager import SearchManager

class Record(models.Model):

    STATUS_UNDEFINED = 0
    STATUS_MODERATION = 1
    STATUS_PUBLISHED = 2
    STATUS_CLOSED = 3

    STATUSES = (
        (STATUS_UNDEFINED, "Неизвестено"),
        (STATUS_MODERATION, "На модерации"),
        (STATUS_PUBLISHED, "Опубликована"),
        (STATUS_CLOSED, "Закрыта"),
    )

    title = models.CharField(max_length=128, blank=False)
    story = models.TextField(null=True, blank=True)
    compiled_story = models.TextField(null=True, blank=True)

    url = models.CharField(max_length=128, blank=True)

    category = models.ForeignKey(Category, null=True, blank=True, db_index=True)

    author = models.ForeignKey(User, db_index=True)

    create_date = models.DateTimeField(auto_now_add=True, db_index=True)
    publish_date = models.DateTimeField(null=True, blank=True, db_index=True)

    views = models.IntegerField(default=0, db_index=True)
    rating = models.IntegerField(default=0, db_index=True)

    meta_title = models.CharField(max_length=256, null=True, blank=True)
    meta_description = models.CharField(max_length=200, null=True, blank=True)
    meta_keywords = models.CharField(max_length=256, null=True, blank=True)

    status = models.IntegerField(choices=STATUSES, default=STATUS_UNDEFINED)

    objects = SearchManager()

    def get_page_url(self):
        return "/%s/%s-%s.html" % (self.category.url, self.pk, self.url)

    def uid(self):
        try:
            return Comment.calculate_url(
                "/%s/%s-%s.html" % (self.category.url, self.pk, self.url)
            )

        except Exception, e:
            return 0


    def _compile_story(self):
        compiler = Compiler()
        compiler.compile(self)
        self.save()

    def filtered_title(self):
        return self.title

    def _check_compiled_story(self):
        if not self.compiled_story:
            self._compile_story()
            
    def short_story(self):
        self._check_compiled_story()
        parts = self.compiled_story.split("""<!-- pagebreak -->""")
        return parts[0]

    def full_story(self):
        self._check_compiled_story()
        try:
            parts = self.compiled_story.split("""<!-- pagebreak -->""")
            return parts[1]
        except Exception, e:
            return self.compiled_story


class RecordImage(models.Model):
    image = models.CharField(max_length=255, blank=False, unique=True, db_index=True)
    thumbnail = models.CharField(max_length=255, blank=True, null=True)
    upload_date = models.DateTimeField(auto_now_add=True)
    record = models.ForeignKey(Record, null=True, default=None, blank=True)
